package com.hopes.bizz.poll.hj212.server.handler;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DataHandlerChain implements HJ212DataHandler {
    private List<HJ212DataHandler> handlerList = new ArrayList<HJ212DataHandler>();
    //标识当前任务处理索引
    private ThreadLocal<Integer> indexs = new ThreadLocal<>();

    @Override
    public boolean handler(String data, DataHandlerChain chain) throws DataHandlerException{
        int index = indexs.get();
        if(index == handlerList.size()){
            return false;
        }

        HJ212DataHandler handler = handlerList.get(index);
        index ++;
        indexs.set(index);
        return handler.handler(data, chain);
    }

    /**
     * 添加数据处理类
     * @param handler
     * @return
     */
    public DataHandlerChain addHandler(HJ212DataHandler handler){
        this.handlerList.add(handler);
        return this;
    }

    public void setHandlerList(List<HJ212DataHandler> handlerList) {
        this.handlerList = handlerList;
    }

    /**
     * 开始处理数据
     * @param data
     */
    public void startHandler(String data)throws DataHandlerException{
        log.debug("开始解析数据 ==> data={},ThreadId={}", data,Thread.currentThread());
        indexs.set(0);
        boolean handlerResult = this.handler(data, this);
        log.info("数据解析结果 ==> handlerResult={}", handlerResult);
        if(!handlerResult){
            log.info("当前数据未能处理 ==> data={}", data);
        }
    }
}
